package com.wenzhoujie;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import android.app.ActionBar.LayoutParams;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView.ScaleType;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.socialize.facebook.controller.utils.ToastUtil;
import com.wenzhoujie.library.title.SDTitleSimple.SDTitleSimpleListener;
import com.wenzhoujie.library.title.SDTitleTwoRightButton.SDTitleTwoRightButtonListener;
import com.wenzhoujie.library.utils.SDResourcesUtil;
import com.wenzhoujie.library.utils.SDViewBinder;
import com.wenzhoujie.library.utils.SDViewUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lingou.www.R;
import com.sunday.eventbus.SDBaseEvent;
import com.wenzhoujie.adapter.MerchantDetailAdapter;
import com.wenzhoujie.adapter.SuperMarketIndexCateAdapter;
import com.wenzhoujie.adapter.SuperMarketIndexGoodsAdapter;
import com.wenzhoujie.app.App;
import com.wenzhoujie.app.AppHelper;
import com.wenzhoujie.constant.Constant.TitleType;
import com.wenzhoujie.customview.AbSlidingPlayView;
import com.wenzhoujie.customview.AbSlidingPlayView.AbOnItemClickListener;
import com.wenzhoujie.customview.AbSlidingPlayView.AbOnTouchListener;
import com.wenzhoujie.customview.SDGridViewInScroll;
import com.wenzhoujie.event.EventTagJpush;
import com.wenzhoujie.fragment.HomeAdvsFragment;
import com.wenzhoujie.fragment.ChaoshiAdvsFragment;
import com.wenzhoujie.fragment.ChaoshiCateFragment;
import com.wenzhoujie.fragment.HomeRecommendEvnetFragment;
import com.wenzhoujie.fragment.HomeRecommendGuessFragment;
import com.wenzhoujie.fragment.HomeRecommendSupplierFragment;
import com.wenzhoujie.fragment.HomeTitleBarFragment2;
import com.wenzhoujie.fragment.MerchantDetailBriefFragment;
import com.wenzhoujie.fragment.MerchantDetailCommentFragment;
import com.wenzhoujie.fragment.MerchantDetailCouponFragment;
import com.wenzhoujie.fragment.MerchantDetailDealsFragment;
import com.wenzhoujie.fragment.MerchantDetailGoodsFragment;
import com.wenzhoujie.fragment.MerchantDetailInfoFragment;
import com.wenzhoujie.fragment.MerchantDetailOtherMerchantFragment;
import com.wenzhoujie.http.InterfaceServer;
import com.wenzhoujie.model.IndexActAdvsModel;
import com.wenzhoujie.model.IndexActDeal_listModel;
import com.wenzhoujie.model.MerchantShopItem;
import com.wenzhoujie.model.MerchantdetailClassifyModel;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.SearchConditionModel;
import com.wenzhoujie.model.ShopGoodsModel;
import com.wenzhoujie.model.SmCatesModel;
import com.wenzhoujie.model.act.IndexActNewModel;
import com.wenzhoujie.model.act.MerchantitemChaoshiActModel;
import com.wenzhoujie.utils.IocUtil;
import com.wenzhoujie.utils.JsonUtil;
import com.wenzhoujie.utils.SDInterfaceUtil;
import com.wenzhoujie.utils.SDTypeParseUtil;
import com.wenzhoujie.utils.ViewInject;

/**
 * 超市门店详情
 * 
 * @author js02
 * 
 */
public class SuperMarketDetailActivity extends BaseActivity {

	/** 商家id */
	public static final String EXTRA_MERCHANT_ID = "extra_merchant_id";
	public static final String EXTRA_MERCHANT_TITLE = "extra_merchant_title";
	public static final String EXTRA_MERCHANT_SUPPLYER_ID = "extra_merchant_sid";

	//private PopupWindow pop;
	private String id = null;
	//从item中获取吧
	//private String supplyer_id = null;
	private String title = "超市";
	
	@ViewInject(id = R.id.frag_sm_advs_spv_ad)
	private AbSlidingPlayView mSpvAd = null;
	private List<IndexActAdvsModel> mListAdvModel = null;
	
	private SuperMarketIndexGoodsAdapter mGoodsAdapter = null;
	private List<MerchantShopItem> mListGoodsModel  = new ArrayList<MerchantShopItem>();
	//@ViewInject(id = R.id.frag_sm_items_today)
	//private GridView mGvTodayGoods = null;
	//private FrameLayout mGvTodayGoods = null;
	
	private SuperMarketIndexCateAdapter mCateAdapter = null;
	private List<SmCatesModel> mListCateModel = null;
	@ViewInject(id = R.id.frag_sm_cates)
	private SDGridViewInScroll mGvCate = null;
	
//	@ViewInject(id = R.id.frag_sm_cates_ll)
//	private LinearLayout mCatesll = null;
	@ViewInject(id = R.id.item_jrtj_line1)
	private LinearLayout mJrtjLine1 = null;
	@ViewInject(id = R.id.item_jrtj_line2)
	private LinearLayout mJrtjLine2 = null;
	@ViewInject(id = R.id.item_jrtj_line3)
	private LinearLayout mJrtjLine3 = null;
	
	@ViewInject(id = R.id.item_jrtj_deals_iv_image1)
	private ImageView mJrtjImg1 = null;
	@ViewInject(id = R.id.item_jrtj_deals_iv_image2)
	private ImageView mJrtjImg2 = null;
	@ViewInject(id = R.id.item_jrtj_deals_iv_image3)
	private ImageView mJrtjImg3 = null;
	@ViewInject(id = R.id.item_jrtj_deals_iv_image4)
	private ImageView mJrtjImg4 = null;
	@ViewInject(id = R.id.item_jrtj_deals_iv_image5)
	private ImageView mJrtjImg5 = null;
	@ViewInject(id = R.id.item_jrtj_deals_iv_image6)
	private ImageView mJrtjImg6 = null;
	@ViewInject(id = R.id.item_jrtj_deals_iv_image7)
	private ImageView mJrtjImg7 = null;
	@ViewInject(id = R.id.item_jrtj_deals_iv_image8)
	private ImageView mJrtjImg8 = null;
	@ViewInject(id = R.id.item_jrtj_deals_iv_image9)
	private ImageView mJrtjImg9 = null;
	
	@ViewInject(id = R.id.item_jrtj_today_name1)
	private TextView mJrtjName1 = null;
	@ViewInject(id = R.id.item_jrtj_today_name2)
	private TextView mJrtjName2 = null;
	@ViewInject(id = R.id.item_jrtj_today_name3)
	private TextView mJrtjName3 = null;
	@ViewInject(id = R.id.item_jrtj_today_name4)
	private TextView mJrtjName4 = null;
	@ViewInject(id = R.id.item_jrtj_today_name5)
	private TextView mJrtjName5 = null;
	@ViewInject(id = R.id.item_jrtj_today_name6)
	private TextView mJrtjName6 = null;
	@ViewInject(id = R.id.item_jrtj_today_name7)
	private TextView mJrtjName7 = null;
	@ViewInject(id = R.id.item_jrtj_today_name8)
	private TextView mJrtjName8 = null;
	@ViewInject(id = R.id.item_jrtj_today_name9)
	private TextView mJrtjName9 = null;

	@ViewInject(id = R.id.item_jrtj_today_price1)
	private TextView mJrtjPri1 = null;
	@ViewInject(id = R.id.item_jrtj_today_price2)
	private TextView mJrtjPri2 = null;
	@ViewInject(id = R.id.item_jrtj_today_price3)
	private TextView mJrtjPri3 = null;
	@ViewInject(id = R.id.item_jrtj_today_price4)
	private TextView mJrtjPri4 = null;
	@ViewInject(id = R.id.item_jrtj_today_price5)
	private TextView mJrtjPri5 = null;
	@ViewInject(id = R.id.item_jrtj_today_price6)
	private TextView mJrtjPri6 = null;
	@ViewInject(id = R.id.item_jrtj_today_price7)
	private TextView mJrtjPri7 = null;
	@ViewInject(id = R.id.item_jrtj_today_price8)
	private TextView mJrtjPri8 = null;
	@ViewInject(id = R.id.item_jrtj_today_price9)
	private TextView mJrtjPri9 = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setmTitleType(TitleType.TITLE_SIMPLE);
		setContentView(R.layout.frag_merchant_supermarket);
		IocUtil.initInjectedView(this);
		init();
		
	}

	private void init() {
		initIntentData(getIntent());
		initTitle();
		initAbSlidingPlayView();
		bindAdvs();
		bindDefaultCate();
		requestData();
	}

	private void initTitle() {
		
		mTitleSimple.setmListener(new SDTitleSimpleListener()
		{

			@Override
			public void onRightButtonCLick_SDTitleSimple(View v)
			{
				
					//mFragWebview.startLoadData();
					finish();
		
			}

			@Override
			public void onLeftButtonCLick_SDTitleSimple(View v)
			{
					finish();
			}
		});
		//mTitleSimple.setRightText("刷新");
		mTitleSimple.setRightText("");

		if (title != null)
		{
			mTitleSimple.setTitleTop(title);
		}
		
	}
	
	public String getSmName()
	{ //返回超市名稱
		return title;
	}
	public String getSmId()
	{ //返回超市id
		return id;
	}
	
	
	private void initIntentData(Intent intent) {
		id = intent.getStringExtra(EXTRA_MERCHANT_ID);
		if (intent.getStringExtra(EXTRA_MERCHANT_TITLE) != null)
			title = intent.getStringExtra(EXTRA_MERCHANT_TITLE);
		//supplyer_id = intent.getStringExtra(EXTRA_MERCHANT_SUPPLYER_ID);
	}

	private void bindDefaultGoods(){
		//this.mListGoodsModel = new ArrayList<MerchantShopItem>();
		//this.mGoodsAdapter = new SuperMarketIndexGoodsAdapter(this.mListGoodsModel, this);
		//this.mGvTodayGoods.setAdapter(mGoodsAdapter);

		int nowIdx = 0;
		if(mListGoodsModel.size()>nowIdx)
		{
			handleBindGoods(mJrtjImg1,mJrtjName1,mJrtjPri1, nowIdx);
		}
		else
		{
			hideBindGoods(mJrtjImg1,mJrtjName1,mJrtjPri1);
		}
		nowIdx = 1;
		if(mListGoodsModel.size()>nowIdx)
		{
			handleBindGoods(mJrtjImg2,mJrtjName2,mJrtjPri2, nowIdx);
		}
		else
		{
			hideBindGoods(mJrtjImg2,mJrtjName2,mJrtjPri2);
		}
		nowIdx = 2;
		if(mListGoodsModel.size()>nowIdx)
		{
			handleBindGoods(mJrtjImg3,mJrtjName3,mJrtjPri3, nowIdx);
		}
		else
		{
			hideBindGoods(mJrtjImg3,mJrtjName3,mJrtjPri3);
		}
		nowIdx = 3;
		if(mListGoodsModel.size()>nowIdx)
		{
			handleBindGoods(mJrtjImg4,mJrtjName4,mJrtjPri4, nowIdx);
		}
		else
		{
			hideBindGoods(mJrtjImg4,mJrtjName4,mJrtjPri4);
		}
		nowIdx = 4;
		if(mListGoodsModel.size()>nowIdx)
		{
			handleBindGoods(mJrtjImg5,mJrtjName5,mJrtjPri5, nowIdx);
		}
		else
		{
			hideBindGoods(mJrtjImg5,mJrtjName5,mJrtjPri5);
		}
		nowIdx = 5;
		if(mListGoodsModel.size()>nowIdx)
		{
			handleBindGoods(mJrtjImg6,mJrtjName6,mJrtjPri6, nowIdx);
		}
		else
		{
			hideBindGoods(mJrtjImg6,mJrtjName6,mJrtjPri6);
		}
		nowIdx = 6;
		if(mListGoodsModel.size()>nowIdx)
		{
			handleBindGoods(mJrtjImg7,mJrtjName7,mJrtjPri7, nowIdx);
		}
		else
		{
			hideBindGoods(mJrtjImg7,mJrtjName7,mJrtjPri7);
		}
		nowIdx = 7;
		if(mListGoodsModel.size()>nowIdx)
		{
			handleBindGoods(mJrtjImg8,mJrtjName8,mJrtjPri8, nowIdx);
		}
		else
		{
			hideBindGoods(mJrtjImg8,mJrtjName8,mJrtjPri8);
		}
		nowIdx = 8;
		if(mListGoodsModel.size()>nowIdx)
		{
			handleBindGoods(mJrtjImg9,mJrtjName9,mJrtjPri9, nowIdx);
		}
		else
		{
			hideBindGoods(mJrtjImg9,mJrtjName9,mJrtjPri9);
		}
	}
	private void handleBindGoods(ImageView img,TextView name,TextView pric,int idx)
	{
		//img.setMaxHeight(img.getMeasuredWidth());
		//img.setMinimumHeight(img.getMeasuredWidth());
		///SDViewBinder.setImageView(img, mListGoodsModel.get(idx).getImg());
		SDViewBinder.setImageViewByImagesScale(img, mListGoodsModel.get(idx).getImg());
		SDViewBinder.setTextView(name, mListGoodsModel.get(idx).getName());
		SDViewBinder.setTextView(pric, "￥"+String.valueOf(mListGoodsModel.get(idx).getCurrent_price()));
		final String nowId = Integer.toString(mListGoodsModel.get(idx).getId());
		img.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(App.getApplication(), TuanDetailActivity.class);
				intent.putExtra(TuanDetailActivity.EXTRA_GOODS_ID, nowId);
				intent.putExtra(TuanDetailActivity.EXTRA_GOODS_TYPE, 0);
				startActivity(intent);
			}
		});
	}
	private void hideBindGoods(ImageView img,TextView name,TextView pric)
	{
		//img.setMaxHeight(img.getMeasuredWidth());
		img.setVisibility(View.GONE);
		name.setVisibility(View.GONE);
		pric.setVisibility(View.GONE);
	}
	
	
	private void bindDefaultCate(){
		this.mListCateModel = new ArrayList<SmCatesModel>();
		this.mCateAdapter = new SuperMarketIndexCateAdapter(this.mListCateModel, this);
		this.mGvCate.setAdapter(mCateAdapter);
		//int lines = mListCateModel.size()/2;
		//mGvCate.setMinimumHeight(lines*60);
		//mCatesll.setMinimumHeight(lines*50);
	}
	
	private void requestData()
	{
		RequestModel model = new RequestModel();
		model.put("act", "merchantitem_chaoshi");
		model.put("id", id);
		RequestCallBack<String> handler = new RequestCallBack<String>()
		{

			@Override
			public void onStart()
			{
				AppHelper.showLoadingDialog("请稍候...");
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo)
			{
				System.out.println(responseInfo.result);
				MerchantitemChaoshiActModel actModel = JsonUtil.json2Object(responseInfo.result, MerchantitemChaoshiActModel.class);
				if (!SDInterfaceUtil.isActModelNull(actModel))
				{
					if (actModel.getResponse_code() == 1)
					{
						//绑定广告
						mListAdvModel = actModel.getAdvs();
						bindAdvs();
						//绑定今日推荐
						//SDViewUtil.updateAdapterByList(mListGoodsModel, actModel.getRecommend_items(), mGoodsAdapter, false);
						mListGoodsModel = actModel.getRecommend_items();
						bindDefaultGoods();
						//绑定分类
						SDViewUtil.updateAdapterByList(mListCateModel, actModel.getCates(), mCateAdapter, false);
						
					}
				}
			}

			@Override
			public void onFailure(HttpException error, String msg)
			{

			}

			@Override
			public void onFinish()
			{
				dealFinishRequest();
			}
		};
		InterfaceServer.getInstance().requestInterface(model, handler);
	}

	protected void dealFinishRequest()
	{
		AppHelper.hideLoadingDialog();
		//mPtrlvContent.onRefreshComplete();
	}
	
	/**
	 * 绑定头部广告
	 */
	private void bindAdvs()
	{
		mSpvAd.stopPlay();
		if (mListAdvModel != null && mListAdvModel.size() > 0)
		{
			mSpvAd.getViewPager().setCurrentItem(Integer.MAX_VALUE / 2 - Integer.MAX_VALUE / 2 % mListAdvModel.size());

			mSpvAd.removeAllViews();
			IndexActAdvsModel model = null;
			for (int i = 0; i < mListAdvModel.size(); i++)
			{
				model = mListAdvModel.get(i);
				ImageView ivAdv = new ImageView(this);
				ivAdv.setScaleType(ScaleType.FIT_CENTER);
				mSpvAd.addView(ivAdv);
				if (i == 0)
					SDViewBinder.setImageFillScreenWidthByScale(ivAdv, mSpvAd, model.getImg());
				else
					SDViewBinder.setImageView(ivAdv, model.getImg());
			}
		}
		
		mSpvAd.setFocusable(true); 
		mSpvAd.setFocusableInTouchMode(true);
		mSpvAd.requestFocus();   
	}
	
	private void initAbSlidingPlayView()
	{
		mSpvAd.setNavHorizontalGravity(Gravity.CENTER);

		mSpvAd.setOnItemClickListener(new AbOnItemClickListener()
		{
			@Override
			public void onClick(int position)
			{
				if (mListAdvModel != null && mListAdvModel.size() > 0)
				{
					IndexActAdvsModel model = mListAdvModel.get(position);
					clickAd(model);
				}
			}
		});

		mSpvAd.setOnTouchListener(new AbOnTouchListener()
		{

			@Override
			public void onTouch(MotionEvent event)
			{
				// switch (event.getAction())
				// {
				// case MotionEvent.ACTION_DOWN:
				// mSpvAd.stopPlay();
				// break;
				// case MotionEvent.ACTION_UP:
				// mSpvAd.startPlay();
				// break;
				//
				// default:
				// break;
				// }
			}
		});
	}

	/**
	 * 广告被点击
	 * 
	 * @param model
	 */
	private void clickAd(IndexActAdvsModel model)
	{
		if (model != null)
		{
			int type = SDTypeParseUtil.getIntFromString(model.getType(), -1);
			if (type == 7)
			{
				/*
				if (this instanceof MainActivity)
				{
					MainActivity mainActivity = (MainActivity) getActivity();
					mainActivity.setSelectIndex(2, null, true);
				}
				*/
				return;
			}
			Intent intent = IndexActNewModel.createIntentByType(type, model.getData(), true);
			if (intent != null)
			{
				try
				{
					startActivity(intent);
				} catch (Exception e)
				{
					// TODO: handle exception
				}
			}
		}
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		setIntent(intent);
		init();
		super.onNewIntent(intent);
	}
	
	@Override
	public void onEventMainThread(SDBaseEvent event) {
		super.onEventMainThread(event);
		if (EventTagJpush.EVENT_MERCHANTDETAIL_ID.equals(event
				.getEventTagString())) {
			finish();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (App.getApplication().mRuntimeConfig.isNeedRefreshMerchantDetail()) {
			init();
			App.getApplication().mRuntimeConfig
					.setNeedRefreshMerchantDetail(false);
		}
		if (mSpvAd != null)
		{
			mSpvAd.startPlay();
		}
	}
	
	@Override
	protected void onPause(){
		if (mSpvAd != null)
		{
			mSpvAd.stopPlay();
		}
		super.onPause();
	}
}